<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /* 
      平衡二叉树，即左右两个子树的高度差小于或者等于1。
      思路：只需要遍历每个节点，然后通过getDepth获取其左右子树的高度，然后判断是否小于等于1
      
      */
      var isBalanced = function (root) {
        //遍历每个节点，先序遍历即可
        let flag = true
        function preOrder(root) {
          if (!root) return
          let numLeft = getDepth(root.left)
          let numRight = getDepth(root.right)
          if (Math.abs(numLeft - numRight) > 1) {
            return (flag = false)
          }
          preOrder(root.left)
          preOrder(root.right)
        }
        preOrder(root)
        return flag
        function getDepth(root) {
          if (!root) return 0
          return Math.max(getDepth(root.left), getDepth(root.right)) + 1
        }
      }
    </script>
  </body>
</html>
